﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

using Newtonsoft.Json;

namespace Utils.Weixin
{
    public class WeixinCryptHelper
    {
        public static string Sha1Sign(string content)
        {
            Encoding encode = Encoding.UTF8;
#if NET6_0 || NET7_0
            SHA1 sha1 =  SHA1.Create();
#else
            SHA1 sha1 = new SHA1CryptoServiceProvider();
#endif

            try
            {
                //创建SHA1对象
                byte[] bytes_in = encode.GetBytes(content);//将待加密字符串转为byte类型
                byte[] bytes_out = sha1.ComputeHash(bytes_in);//Hash运算               
                String result = BitConverter.ToString(bytes_out);//将运算结果转为string类型
                result = result.Replace("-", "").ToUpper();//替换并转为大写
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                sha1.Clear();
            }
        }
        /// <summary>
        /// 解密
        /// </summary>
        public static string Decrypt(string input, string encodingAESKey, out string appId)
        {
            byte[] key = Convert.FromBase64String(encodingAESKey + "=");
            byte[] iv = new byte[16];
            Array.Copy(key, iv, 16);
            byte[] btmpMsg = Decrypt(input, iv, key);
            int len = BitConverter.ToInt32(btmpMsg, 16);
            len = IPAddress.NetworkToHostOrder(len);

            byte[] bMsg = new byte[len];
            byte[] bAppid = new byte[btmpMsg.Length - 20 - len];
            Array.Copy(btmpMsg, 20, bMsg, 0, len);
            Array.Copy(btmpMsg, 20 + len, bAppid, 0, btmpMsg.Length - 20 - len);
            string oriMsg = Encoding.UTF8.GetString(bMsg);
            appId = Encoding.UTF8.GetString(bAppid);
            return oriMsg;
        }


        /// <summary>
        /// 加密
        /// </summary>
        /// <returns></returns>
        public static string Encrypt(string replyMsg, string timeStamp, string nonce, string appId, string token, string encodingAESKey)
        {
            if (encodingAESKey.Length != 43)
            {
                throw Error.DefaultError("无效秘钥");
            }
            string raw;
            try
            {
                raw = Encrypt(replyMsg, encodingAESKey, appId);
            }
            catch (Exception)
            {
                throw Error.DefaultError("无效秘钥");
            }
            string msgSigature = Signature(token, timeStamp, nonce, raw);
            var encryptMsg = "";
            string encryptLabelHead = "<Encrypt><![CDATA[";
            string encryptLabelTail = "]]></Encrypt>";
            string msgSigLabelHead = "<MsgSignature><![CDATA[";
            string msgSigLabelTail = "]]></MsgSignature>";
            string timeStampLabelHead = "<TimeStamp><![CDATA[";
            string timeStampLabelTail = "]]></TimeStamp>";
            string nonceLabelHead = "<Nonce><![CDATA[";
            string nonceLabelTail = "]]></Nonce>";
            encryptMsg = encryptMsg + "<xml>" + encryptLabelHead + raw + encryptLabelTail;
            encryptMsg = encryptMsg + msgSigLabelHead + msgSigature + msgSigLabelTail;
            encryptMsg = encryptMsg + timeStampLabelHead + timeStamp + timeStampLabelTail;
            encryptMsg = encryptMsg + nonceLabelHead + nonce + nonceLabelTail;
            encryptMsg += "</xml>";
            return encryptMsg;

        }

        public static string Signature(string token, string timeStamp, string nonce, string msgEncrypt)
        {
            List<string> al = new List<string>();
            al.Add(token);
            al.Add(timeStamp);
            al.Add(nonce);
            al.Add(msgEncrypt);
            al.Sort(StringComparer.CurrentCulture);
            string raw = al.Join("");
            SHA1 sha;
            ASCIIEncoding enc;
            try
            {
                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(raw);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                string hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
                return hash;
            }
            catch (Exception)
            {
                throw Error.DefaultError("签名失败");
            }
        }

        #region 解密

        private static byte[] Decrypt(string text, byte[] iv, byte[] key)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.KeySize = 256;
            aes.BlockSize = 128;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;
            aes.Key = key;
            aes.IV = iv;
            var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
            byte[] xBuff = null;
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Convert.FromBase64String(text);
                    byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32];
                    Array.Copy(xXml, msg, xXml.Length);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = Decode(ms.ToArray());
            }
            return xBuff;
        }


        private static byte[] Decode(byte[] decrypted)
        {
            int pad = decrypted[^1];
            if (pad < 1 || pad > 32)
            {
                pad = 0;
            }
            byte[] res = new byte[decrypted.Length - pad];
            Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
            return res;
        }

        #endregion

        public static string Encrypt(string input, string encodingAESKey, string appid)
        {
            byte[] Key;
            Key = Convert.FromBase64String(encodingAESKey + "=");
            byte[] Iv = new byte[16];
            Array.Copy(Key, Iv, 16);
            string Randcode = StringHelper.GetRandomCode(16, RandCodeType.LETTER | RandCodeType.NUMBER);
            byte[] bRand = Encoding.UTF8.GetBytes(Randcode);
            byte[] bAppid = Encoding.UTF8.GetBytes(appid);
            byte[] btmpMsg = Encoding.UTF8.GetBytes(input);
            byte[] bMsgLen = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(btmpMsg.Length));
            byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bAppid.Length + btmpMsg.Length];

            Array.Copy(bRand, bMsg, bRand.Length);
            Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length);
            Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length);
            Array.Copy(bAppid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bAppid.Length);

            return Encrypt(bMsg, Iv, Key);

        }


        private static string Encrypt(byte[] input, byte[] Iv, byte[] Key)
        {
            var aes = new RijndaelManaged();
            //秘钥的大小，以位为单位
            aes.KeySize = 256;
            //支持的块大小
            aes.BlockSize = 128;
            //填充模式
            //aes.Padding = PaddingMode.PKCS7;
            aes.Padding = PaddingMode.None;
            aes.Mode = CipherMode.CBC;
            aes.Key = Key;
            aes.IV = Iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff = null;

            #region 自己进行PKCS7补位，用系统自己带的不行
            byte[] msg = new byte[input.Length + 32 - input.Length % 32];
            Array.Copy(input, msg, input.Length);
            byte[] pad = KCS7Encoder(input.Length);
            Array.Copy(pad, 0, msg, input.Length, pad.Length);
            #endregion

            #region 注释的也是一种方法，效果一样
            //ICryptoTransform transform = aes.CreateEncryptor();
            //byte[] xBuff = transform.TransformFinalBlock(msg, 0, msg.Length);
            #endregion

            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    cs.Write(msg, 0, msg.Length);
                }
                xBuff = ms.ToArray();
            }

            string output = Convert.ToBase64String(xBuff);
            return output;
        }
        private static byte[] KCS7Encoder(int text_length)
        {
            int block_size = 32;
            // 计算需要填充的位数
            int amount_to_pad = block_size - (text_length % block_size);
            if (amount_to_pad == 0)
            {
                amount_to_pad = block_size;
            }
            // 获得补位所用的字符
            char pad_chr = Chr(amount_to_pad);
            string tmp = "";
            for (int index = 0; index < amount_to_pad; index++)
            {
                tmp += pad_chr;
            }
            return Encoding.UTF8.GetBytes(tmp);
        }
        /**
         * 将数字转化成ASCII码对应的字符，用于对明文进行补码
         * 
         * @param a 需要转化的数字
         * @return 转化得到的字符
         */
        private static char Chr(int a)
        {
            byte target = (byte)(a & 0xFF);
            return (char)target;
        }
  
    }
}
